<style>
.outer {
  position: relative;
  height: 460px;
}
.toolbar {
  width: 100%;
  /* border: 1px solid #ccc; */
  position: relative;
  z-index: 125;
}
.text {
  border: 1px solid #ccc;
  /* min-height: 400px; */
  height: 400px;
}
.boxerl {
  position: relative;
  width: 100%;
  overflow-x: hidden;
  overflow-y: hidden;
  height: 320px;
}
.boxerh {
  z-index: 120;
  top: 66px;
  position: absolute;
  width: 100%;
  height: 400px;
  overflow-y: auto;
  overflow-x: hidden;
}
.scollbar {
  width: 100%;
  overflow-x: auto;
}
.blankinner {
  width: 768px;
  height: 5px;
  border: 1px solid white;
}
</style>

<template>
  <div>
    <Modal
      :value="modalState"
      :title="title"
      :loading="loading"
      ok-text="保存"
      @on-ok="handleSubmit"
      @on-cancel="cancel"
      width="50%"
    >
      <Form
        ref="pgoodsModal"
        :model="row"
        :rules="ruleValidate"
        style="width: 100%; margin-left: 50px;"
        :label-width="100"
      >
        <FormItem prop="name" style="width: 300px;" label="商品：">
          <Select v-model="row.name" placeholder="请选择商品" :disabled="row.state === 1 ? true : false">
            <Option v-for="item in goodsList" :value="item.name" :key="item.id">{{ item.name }}</Option>
          </Select>
        </FormItem>
        <FormItem prop="price" label="商品价格：" style="width: 300px">
          <Input
            :disabled="row.state === 1 ? true : false"
            type="text"
            v-model="row.price"
            placeholder="请输入商品价格"
          />
        </FormItem>
        <FormItem prop="pprice" label="拼团价格：" style="width: 300px">
          <Input
            :disabled="row.state === 1 ? true : false"
            type="text"
            v-model="row.pprice"
            placeholder="请输入拼团价格"
          />
        </FormItem>
        <FormItem prop="time" label="生效日期：" style="width: 300px">
          <DatePicker
            :disabled="row.state === 1 ? true : false"
            v-model="row.time"
            format="yyyy-MM-dd"
            type="daterange"
            style="width: 100%"
            placeholder="请选择生效日期"
          ></DatePicker>
        </FormItem>
        <FormItem prop="num" label="成团人数：" style="width: 300px">
          <Input
            :disabled="row.state === 1 ? true : false"
            type="text"
            v-model="row.num"
            placeholder="请输入成团人数"
          />
        </FormItem>
        <FormItem v-if="row.state !== 1" prop="img" label="拼团图片：" style="width: 80%">
          <upload-img @upload-success="handleUpload" :folder="folder" :row="row"></upload-img>
        </FormItem>
        <FormItem v-if="row.state === 1" prop="img" label="拼团图片：" style="width: 80%">
          <img :src="row.img ? row.host+row.img : ''" style="width: 60px; height: 60px;">
        </FormItem>
        <FormItem prop="content" label="拼团内容：" style="width: 95%">
          <!-- <Input :disabled="row.state === 1" v-model="row.des" type="textarea" placeholder="请输入任务要求" /> -->
          <!-- <div ref="editor" style="text-align:left;">
          </div>-->
          <div class="outer">
            <div id="scoller" class="scollbar" @scroll="doThis()">
              <div class="blankinner"></div>
            </div>
            <div id="inner" class="boxerl">
              <div id="div1" class="toolbar">
                <Button
                  :disabled="row.state === 1"
                  icon="md-trash"
                  size="large"
                  style="border: none; margin-top: -3px"
                  @click="handleClear"
                ></Button>
              </div>
            </div>
            <!--<div style="padding: 5px 0; color: #ccc">menu list</div>-->
            <div class="boxerh">
              <div id="div2" class="text">
                <!--可使用 min-height 实现编辑区域自动增加高度-->
                <!-- <p>请输入内容</p> -->
              </div>
            </div>
          </div>
        </FormItem>
        <FormItem prop="topState" label="是否置顶：" style="width: 300px">
          <i-switch :disabled="row.state === 1 ? true : false" v-model="row.topState"/>
        </FormItem>
      </Form>
    </Modal>
  </div>
</template>
<script>
import { mapActions, mapState } from 'vuex'
import UploadImg from '_c/upload-img'
import { getToken } from '../../libs/util'
import E from 'wangeditor'
export default {
  name: 'PgoodsModal',
  components: {
    UploadImg
  },
  data () {
    const reg = /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/
    const validateDate = (rule, value, callback) => {
      const start = value[0]
      const end = value[1]
      if (start === '' && end === '') {
        callback(new Error('请选择生效日期！'))
      } else {
        callback()
      }
    }

    const validateMoney = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('金额不能为空!'))
      } else {
        if (!reg.test(value)) {
          callback(new Error('请输入正确的金额！'))
        } else {
          callback()
        }
      }
    }

    const validateNum = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('人数不能为空!'))
      } else {
        if (!reg.test(value)) {
          callback(new Error('请输入正确的人数！'))
        } else {
          callback()
        }
      }
    }

    return {
      title: '',
      imgUrl: '',
      time: [],
      loading: true,
      folder: 'pgoods',
      token: getToken(),
      ruleValidate: {
        name: [
          {
            required: true,
            message: '请选择商品',
            trigger: 'change'
          }
        ],
        price: [
          {
            validator: validateMoney,
            trigger: 'blur'
          }
        ],
        pprice: [
          {
            validator: validateMoney,
            trigger: 'blur'
          }
        ],
        time: [
          {
            validator: validateDate,
            trigger: 'blur'
          }
        ],
        num: [
          {
            validator: validateNum,
            trigger: 'blur'
          }
        ]
      }
    }
  },
  updated () {
    if (this.row.id && this.row.id !== '') {
      this.title = '编辑拼团信息'
    } else {
      this.title = '添加拼团'
    }
  },
  computed: {
    ...mapState({
      row: state => state.pgoods.row,
      modalState: state => state.modal.modalState,
      goodsList: state => state.goodService.goodsList
    })
  },
  methods: {
    ...mapActions(['updateModalState']),
    changeLoading () {
      this.loading = false
      this.$nextTick(() => {
        this.loading = true
      })
    },
    handleClear () {
      this.editor.txt.clear()
    },
    doThis () {
      var elem = document.getElementById('scoller')
      var inner = document.getElementById('inner')
      inner.scrollLeft = elem.scrollLeft
    },
    handleSubmit () {
      this.$refs.pgoodsModal.validate(valid => {
        if (!valid) {
          return this.changeLoading()
        }

        this.$emit('pgoods-valid', {
          id: this.row.id,
          name: this.row.name,
          price: this.row.price,
          pprice: this.row.pprice,
          num: this.row.num,
          btime:
            this.row.time && this.row.time[0]
              ? this.$moment(this.row.time[0], this.$moment.ISO_8601).format(
                'YYYY-MM-DD'
              )
              : '',
          etime:
            this.row.time && this.row.time[1]
              ? this.$moment(this.row.time[1], this.$moment.ISO_8601).format(
                'YYYY-MM-DD'
              )
              : '',
          img: this.row.img,
          content: this.editorContent ? this.editorContent : this.row.content,
          top: this.row.topState === true ? 1 : undefined
          // state: this.row.openState === true ? 0 : 1
        })
      })
    },
    cancel () {
      this.row.img = ''
      this.updateModalState(false)
      this.$refs['pgoodsModal'].resetFields()
    },
    handleUpload (url) {
      this.row.img = url
    }
  },
  created () {
    window.addEventListener('scroll', this.doThis)
  },
  mounted () {
    let self = this
    // //console.log(this.graphicList)
    this.actionUrl =
      process.env.NODE_ENV === 'development'
        ? '/api/upload?folder=task'
        : 'http://rbackapi.baisha.work/upload?folder=task'
    this.editor = new E('#div1', '#div2')
    // this.editor = new E(this.$refs.editor)
    this.editor.customConfig.onchange = html => {
      this.editorContent = html
      // this.$refs.showContent.innerHTML = html
    }
    // //console.log(this.row.content)
    // editor.customConfig.uploadImgShowBase64 = true
    this.editor.customConfig.withCredentials = true
    // this.editor.customConfig.debug = true
    this.editor.customConfig.uploadImgServer = this.actionUrl
    this.editor.customConfig.uploadImgMaxSize = 500 * 1024
    this.editor.customConfig.uploadImgHeaders = {
      agent: 'Web',
      token: this.token
    }
    // editor.customConfig.uploadImgParams = {
    //   // 如果版本 <=v3.1.0 ，属性值会自动进行 encode ，此处无需 encode
    //   // 如果版本 >=v3.1.1 ，属性值不会自动 encode ，如有需要自己手动 encode
    //   token: 'abcdef12345'
    // }
    this.editor.customConfig.uploadImgHooks = {
      before (xhr, editor, files) {
        // 图片上传之前触发
        // xhr 是 XMLHttpRequst 对象，editor 是编辑器对象，files 是选择的图片文件
        // 如果返回的结果是 {prevent: true, msg: 'xxxx'} 则表示用户放弃上传
        // return {
        //     prevent: true,
        //     msg: '放弃上传'
        // }
      },
      success (xhr, editor, result) {
        // 图片上传并返回结果，图片插入成功之后触发
        // xhr 是 XMLHttpRequst 对象，editor 是编辑器对象，result 是服务器端返回的结果
        // //console.log(editor)
        // //console.log(result)
      },
      fail (xhr, editor, result) {
        this.$Notice.warning({
          title: '文件大小不正确',
          desc: '请上传3M以下大小的图片'
        })
        // 图片上传并返回结果，但图片插入错误时触发
        // xhr 是 XMLHttpRequst 对象，editor 是编辑器对象，result 是服务器端返回的结果
      },
      error (xhr, editor) {
        // 图片上传出错时触发
        // xhr 是 XMLHttpRequst 对象，editor 是编辑器对象
      },
      timeout (xhr, editor) {
        // 图片上传超时时触发
        // xhr 是 XMLHttpRequst 对象，editor 是编辑器对象
      },

      // 如果服务器端返回的不是 {errno:0, data: [...]} 这种格式，可使用该配置
      // （但是，服务器端返回的必须是一个 JSON 格式字符串！！！否则会报错）
      customInsert (insertImg, result, editor) {
        // 图片上传并返回结果，自定义插入图片的事件（而不是编辑器自动插入图片！！！）
        // insertImg 是插入图片的函数，editor 是编辑器对象，result 是服务器端返回的结果

        // 举例：假如上传图片成功后，服务器端返回的是 {url:'....'} 这种格式，即可这样插入图片：
        let url = result.host + result.data
        insertImg(url)
        // result 必须是一个 JSON 格式字符串！！！否则报错
      }
    }
    this.editor.customConfig.customAlert = function (info) {
      // info 是需要提示的内容
      self.$Notice.warning({
        title: '文件大小不正确',
        desc: '请上传500kb以下大小的图片'
      })
    }
    this.editor.create()
    this.editor.customConfig.pasteFilterStyle = false
    this.editor.txt.html(this.row.content)
    if (this.row.state === 1) {
      this.editor.$textElem.attr('contenteditable', false)
    }
  }
}
</script>
